package com.yuyan.openapi.handler;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.asymmetric.AsymmetricAlgorithm;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import cn.hutool.json.JSONUtil;

import java.nio.charset.StandardCharsets;
import java.security.KeyPair;

/**
 * RSA加密/解密处理器
 */
public class RsaEncryptDecryptHandler implements EncryptDecryptHandler {

    /**
     * 生成密钥对
     *
     * @return
     */
    @Override
    public KeyPair generateKeyPair() {
        return SecureUtil.generateKeyPair(AsymmetricAlgorithm.RSA.getValue());
    }

    /**
     * 加密明文
     *
     * @param object    对象
     * @param publicKey 公钥
     * @return
     */
    @Override
    public String encryptByPublicKey(Object object, String publicKey) {
        String plainText = JSONUtil.toJsonStr(object);
        RSA rsa = SecureUtil.rsa(null, publicKey);
        return rsa.encryptBase64(plainText, StandardCharsets.UTF_8, KeyType.PublicKey);
    }

    /**
     * 加密明文
     *
     * @param object     对象
     * @param privateKey 私钥
     * @return
     */
    @Override
    public String encryptByPrivateKey(Object object, String privateKey) {
        RSA rsa = SecureUtil.rsa(privateKey, null);
        String plainText = JSONUtil.toJsonStr(object);
        return rsa.encryptBase64(plainText, StandardCharsets.UTF_8, KeyType.PrivateKey);
    }

    /**
     * 解密密文
     *
     * @param encryptText 密文文本
     * @param publicKey   公钥
     * @return
     */
    @Override
    public String decryptByPublicKey(String encryptText, String publicKey) {
        RSA rsa = SecureUtil.rsa(null, publicKey);
        return rsa.decryptStr(encryptText, KeyType.PublicKey, StandardCharsets.UTF_8);
    }

    /**
     * 解密密文
     *
     * @param encryptText 密文文本
     * @param privateKey  私钥
     * @return
     */
    @Override
    public String decryptByPrivateKey(String encryptText, String privateKey) {
        RSA rsa = SecureUtil.rsa(privateKey, null);
        return rsa.decryptStr(encryptText, KeyType.PrivateKey, StandardCharsets.UTF_8);
    }

    public static void main(String[] args) {
        RsaEncryptDecryptHandler handler = new RsaEncryptDecryptHandler();
        KeyPair keyPair = handler.generateKeyPair();
        System.out.println("公钥" + handler.getPublicKey(keyPair));
        System.out.println("私钥" + handler.getPrivateKey(keyPair));
    }
}
